package com.ssy.lingxi.sms.serviceImpl;

import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.sms.api.common.ServiceTypeEnum;
import com.ssy.lingxi.sms.api.common.TencentConfigEnum;
import com.ssy.lingxi.sms.api.common.TencentErrorCodeEnum;
import com.ssy.lingxi.sms.api.entity.SmsSendMsg;
import com.ssy.lingxi.sms.api.model.SmsVO;
import com.ssy.lingxi.sms.entity.SmsConfig;
import com.ssy.lingxi.sms.entity.Template;
import com.ssy.lingxi.sms.repository.TemplateRepository;
import com.ssy.lingxi.sms.service.ISmsConfigService;
import com.ssy.lingxi.sms.service.ITencentService;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20190711.models.SendStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * 短信发送
 * @author jw.chen
 * @version 2.0.0
 * @date 2020/7/6
 */
@Service
public class TencentServiceImpl implements ITencentService {

    @Autowired
    private ISmsConfigService smsConfigService;

    @Autowired
    private TemplateRepository templateRepository;

    /**
     * 发送短信
     * @param smsVO
     * @return
     */
    @Override
    public Wrapper<List<SmsSendMsg>> sendSms(SmsVO smsVO, SmsConfig smsConfig){
        //根据业务编号查找短信内容模板id
        String code = smsVO.getCode();
        Template template = templateRepository.findFirstByCode(code);

        //定义返回对象
        List<SmsSendMsg> result = new ArrayList<>();

        if(template != null){
            //获取参数
            String appId = "";
            String sign = "";
            HashMap<String, Object> config = smsConfig.getConfig();
            Object appIdObj = config.get(TencentConfigEnum.appId.getCode());
            if(appIdObj != null){
                appId = appIdObj.toString().substring(0, appIdObj.toString().indexOf(Constants.SPLIT_STR));
            }
            Object signObj = config.get(TencentConfigEnum.sign.getCode());
            if(signObj != null){
                sign = signObj.toString().substring(0, signObj.toString().indexOf(Constants.SPLIT_STR));
            }

            SmsClient smsClient = this.getSmsClient(smsConfig);
            //创建短信发送对象
            SendSmsRequest sendSmsRequest = new SendSmsRequest();
            sendSmsRequest.setSmsSdkAppid(appId);
            sendSmsRequest.setPhoneNumberSet(smsVO.getPhones());
            sendSmsRequest.setSign(sign);
            sendSmsRequest.setTemplateID(String.valueOf(template.getTemplateId()));
            sendSmsRequest.setTemplateParamSet(smsVO.getTemplateParam());

            try {
                //发送短信
                SendSmsResponse sendSmsResponse = smsClient.SendSms(sendSmsRequest);
                SendStatus[] sendStatusSet = sendSmsResponse.getSendStatusSet();

                SendStatus sendStatus;
                SmsSendMsg smsSendMsg;
                for (SendStatus status : sendStatusSet) {
                    smsSendMsg = new SmsSendMsg();
                    sendStatus = status;
                    String statusCode = sendStatus.getCode();
                    String phone = sendStatus.getPhoneNumber();
                    if ("Ok".equals(statusCode)) {
                        smsSendMsg.setPhone(phone);
                        smsSendMsg.setStatus(true);
                    } else {
                        smsSendMsg.setPhone(phone);
                        smsSendMsg.setStatus(false);
                        smsSendMsg.setCode(statusCode);
                        smsSendMsg.setMsg(TencentErrorCodeEnum.getMessage(statusCode));
                    }
                    result.add(smsSendMsg);
                }
                return Wrapper.success(result);
            } catch (TencentCloudSDKException e) {
                //获取错误提示信息
                String msg = e.getMessage();
                String errorCode = msg.substring(0, msg.indexOf("-"));
                SmsSendMsg smsSendMsg = new SmsSendMsg();
                smsSendMsg.setCode(errorCode);
                smsSendMsg.setMsg(TencentErrorCodeEnum.getMessage(errorCode));
                result.add(smsSendMsg);
                return Wrapper.fail(ResponseCode.SERVICE_ERROR, result);
            }
        }else{
            String[] phones = smsVO.getPhones();
            Arrays.stream(phones).forEach(phone -> {
                SmsSendMsg smsSendMsg = new SmsSendMsg();
                smsSendMsg.setPhone(phone);
                smsSendMsg.setCode(String.valueOf(ResponseCode.SMS_TEMPLATE_NOT_EXIST.getCode()));
                smsSendMsg.setMsg(ResponseCode.SMS_TEMPLATE_NOT_EXIST.getMessage());
                result.add(smsSendMsg);
            });
            return Wrapper.success(result);
        }
    }

    /**
     * 批量发送接口
     * @param smsVO
     * @param smsConfig
     * @return
     */
    @Override
    public Wrapper<?> sendBatchSms(SmsVO smsVO, SmsConfig smsConfig) {
        return null;
    }

    /**
     * 获取链接对象
     * @return
     */
    public SmsClient getSmsClient(SmsConfig smsConfig){
        if(smsConfig == null){
            smsConfig = smsConfigService.getSmsConfig(ServiceTypeEnum.Tencent.getCode());
        }
        //获取参数
        HashMap<String, Object> config = smsConfig.getConfig();
        String secretId = "";
        String secretKey = "";
        String region = "";
        Object secretIdObj = config.get(TencentConfigEnum.secretId.getCode());
        if(secretIdObj != null){
            secretId = secretIdObj.toString().substring(0, secretIdObj.toString().indexOf(Constants.SPLIT_STR));
        }
        Object secretKeyObj = config.get(TencentConfigEnum.secretKey.getCode());
        if(secretKeyObj != null){
            secretKey = secretKeyObj.toString().substring(0, secretKeyObj.toString().indexOf(Constants.SPLIT_STR));
        }
        Object regionObj = config.get(TencentConfigEnum.region.getCode());
        if(regionObj != null){
            region = regionObj.toString().substring(0, regionObj.toString().indexOf(Constants.SPLIT_STR));
        }


        // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey
        Credential cred = new Credential(secretId, secretKey);

        // 实例化要请求产品(以cvm为例)的client对象
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setSignMethod(ClientProfile.SIGN_TC3_256);
        //region为产品所在的区
        return new SmsClient(cred, region);
    }

}
